const Service = require("egg").Service;

class CounterService extends Service {
  // 查询所有计数信息
  async getCounter() {
    const result = await this.app.mysql.query(
      "select * from target_list order by id desc"
    );
    return result;
  }

  // 查询单个计数信息
  async getCounterDetail(id) {
    const result = await this.app.mysql.get("target_list", { id });
    return result;
  }

  // 添加计数
  async addCounter(
    target,
    target_amount,
    current_amount,
    add_step,
    decrease_step,
    start_time,
    end_time
  ) {
    try {
      const params = {
        target,
        target_amount,
        current_amount,
        add_step,
        decrease_step,
        start_time,
        end_time,
      };
      const result = await this.app.mysql.insert("target_list", params);
      const insertSuccess = result.affectedRows === 1;

      if (insertSuccess) {
        return result;
      }
      return null;
    } catch (error) {
    }
  }

  // 删除学生信息
  async delStu() {}

  // 更新一个计数器的当前数量
  async updateCurrentAmount(id, current_amount) {
    const result = await this.app.mysql.update("target_list", {
      id,
      current_amount,
    });
    return result;
  }

  // 更新一个计数器信息
  async updateOneCounter(
    id,
    target,
    target_amount,
    current_amount,
    add_step,
    decrease_step,
    start_time,
    end_time
  ) {
    try {
      const params = {
        id,
        target,
        target_amount,
        current_amount,
        add_step,
        decrease_step,
        start_time,
        end_time,
      };
      const result = await this.app.mysql.update("target_list", params);
      const insertSuccess = result.affectedRows === 1;
      if (insertSuccess) {
        return result;
      }
      return null;
    } catch (error) {
    }
  }
  // 删除一个计数器信息
  async deleteOneCounter(id) {
    try {
      const result = await this.app.mysql.query(
        `delete from target_list where id=${id}`
      );
      const deleteSuccess = result.affectedRows === 1;
      if (deleteSuccess) {
        return result;
      }
      return null;
    } catch (error) {}
  }
  // 重置一个计数器信息
  async resetOneCounter(id) {
    try {
      const update =
        "update target_list set target='默认',target_amount='0', current_amount='0',add_step=1,decrease_step=1,start_time='-',end_time='-' where id=" +
        id;
      const result = await this.app.mysql.query(update);
      if (result.affectedRows === 1) {
        return result;
      }
      return null;
    } catch (error) {
    }
  }
}

module.exports = CounterService;
